package com.example.oauthserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.oauthserver.entity.SysUser;
import com.example.oauthserver.mapper.SysUserMapper;
import com.example.oauthserver.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author 龚梦
 * @since 2021-03-29
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService , UserDetailsService {

    @Autowired
    ISysUserService itUserService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.info("用户名：{}",s);
        QueryWrapper<SysUser> tUserWrapper = new QueryWrapper<>();
        tUserWrapper.eq("username",s);
        SysUser sysUser = itUserService.getOne(tUserWrapper);
        if (sysUser==null){
            throw  new UsernameNotFoundException("用户名不正确");
        }
        log.info(passwordEncoder.encode(sysUser.getPassword()));
        return new User(s,sysUser.getPassword(), AuthorityUtils.createAuthorityList("admin"));
    }

}
